package com.douqu.game.main.server;

import com.douqu.game.main.service.PlayerService;
import com.douqu.game.main.service.WorldService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Component
public class ScheduledTask {

    Logger logger = Logger.getLogger(this.getClass());

    /**
     * 每次批量更新的玩家数量
     */
    public final static int BATCH_UPDATE_COUNT = 1000;

    /**
     * 定时保存玩家数据的间隔时间
     * 4分钟
     */
    private final static int SAVE_PLAYER_TIME = 4 * 60 * 1000;

//    /**
//     * 定时保存服务器数据的间隔时间
//     * 4分钟
//     */
//    private final static int SAVE_SERVER_TIME = 4 * 60 * 1000;

    /**
     * 更新时间
     */
    private final static int UPDATE_TIME = 500;

    /**
     * 战斗更新
     */
    private final static int UPDATE_BATTLE_TIME = 1000;

    /**
     * 匹配池任务
     */
    public final static int UPDATE_MATCH_TIME = 1000;

    /**
     * 每天凌晨4点更新所有玩家的段位
     */
    private final static String UPDATE_PLAYER_GRADE_TIME = "0 0 4 * * ?";

//    /**
//     * 每天凌晨5点清除异常被锁的玩家
//     */
//    private final static String CLEAR_LOCK_TIME = "0 0 5 * * ?";
//
//    @Autowired
//    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PlayerService playerService;

    @Autowired
    private WorldService worldService;

    @Scheduled(fixedRate = SAVE_PLAYER_TIME, initialDelay  = 3000)//延迟3秒执行
    public void savePlayer() throws InterruptedException
    {
        worldService.update(GameServer.getInstance().getWorldManager().getWorldInfo());

        playerService.saveOnlinePlayer();
    }

//    @Scheduled(fixedRate = SAVE_SERVER_TIME, initialDelay  = 4000)//延迟4秒执行
//    public void saveServer() throws InterruptedException
//    {
//        worldService.update(GameServer.getInstance().getWorldManager().getWorldInfo());
//    }

    /**
     * 更新
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = UPDATE_TIME, initialDelay = 1000)//延迟1秒执行
    public void updateJob() throws InterruptedException
    {
        GameServer.currentTime = System.currentTimeMillis();
    }

//    /**
//     * 战斗更新
//     * @throws InterruptedException
//     */
//    @Scheduled(fixedDelay = UPDATE_BATTLE_TIME, initialDelay = 9000)//延迟9秒执行
//    public void updateBattleJob() throws InterruptedException
//    {
//    }

    /**
     * 匹配池更新
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay =  UPDATE_MATCH_TIME, initialDelay = 2000)//延迟1秒执行
    public void updateMatch() throws InterruptedException
    {
        GameServer.getInstance().getWorldManager().updateMatch();
    }


    /**
     * 每天凌晨4点执行
     * 超凡大师每天丢失100积分
     * 最强王者每天丢失300积分
     */
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = UPDATE_PLAYER_GRADE_TIME)
    public void updatePlayerGrade() throws Exception
    {
//        //查询超凡大师和最强王者
//        List<Integer> reduceList = DataFactory.getInstance().getDayReduceIntegralList();
//
//        logger.info("Task updatePlayerGrade Start-------------->");
//
//        final List<Player> players = playerMapper.findReduceIntegralPlayers(reduceList);
//        DataFactory dataFactory = DataFactory.getInstance();
//
//        for(Player player : players)
//        {
//            Grade gradeObj = dataFactory.getGameObject(DataFactory.GRADE_KEY, player.getGrade());
//            if(gradeObj != null)
//            {
//                //更新积分和段位
//                player.addIntegral(-gradeObj.getDayReduceIntegral());
//            }
//        }
//
//        String sql = "UPDATE player SET integral = ?, grade = ? WHERE id = ?";
//
//        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter()
//        {
//            public void setValues(PreparedStatement ps, int i)throws SQLException
//            {
//                ps.setInt(1, players.get(i).getIntegral());
//                ps.setInt(2, players.get(i).getGrade());
//                ps.setInt(3, players.get(i).getId());
//                if(i%100 == 0)
//                    logger.info("batchUpdate id:" + players.get(i).getId() + " grade:" + players.get(i).getGrade() + " integral:" + players.get(i).getIntegral());
//            }
//            public int getBatchSize()
//            {
//                return players.size();
//            }
//        });
//
//        PlayerController playerController = null;
//        for(Player player : players)
//        {
//            playerController = GameServer.getInstance().getWorldManager().getPlayerController(player.getId());
//            if(playerController != null)
//            {
//                //在线的
//                playerController.getPlayer().updateIntegral(player.getIntegral(), player.getGrade());
//            }
//        }
//
//        logger.info("Task updatePlayerGrade End-------------->");

    }




}